package com.yy.finvideoplayer.videoview

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Looper
import android.text.TextUtils
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.Toast
import com.yy.finvideoplayer.HandlePlayListener
import com.yy.finvideoplayer.IVideoPlayer
import com.yy.finvideoplayer.IVideoPlayer.Companion.STATE_ERROR
import com.yy.finvideoplayer.IVideoPlayer.Companion.STATE_NORMAL
import com.yy.finvideoplayer.IVideoPlayer.Companion.STATE_PREPARING
import com.yy.finvideoplayer.PlayListener
import com.yy.finvideoplayer.R
import com.yy.finvideoplayer.Util
import com.yy.finvideoplayer.floatwindow.FloatParams
import com.yy.finvideoplayer.floatwindow.FloatWindowHelp
import com.yy.finvideoplayer.manager.ConfigManage
import com.yy.finvideoplayer.media.AndroidMedia
import com.yy.finvideoplayer.media.BaseMedia
import com.yy.finvideoplayer.media.IMediaCallback
import com.yy.finvideoplayer.media.IMediaControl
import com.yy.finvideoplayer.model.PlayerOptions
import com.yy.finvideoplayer.renderview.IRenderView
import com.yy.finvideoplayer.renderview.SufaceRenderView

/**
 * 视频播放器，提供完整控制功能，没有交互ui
 *
 * @Description: MediaVideoView
 * @Author: yiw89
 * @CreateDate: 2025/9/1 16:21
 * @Version: 1.0
 */
open class MediaVideoView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :FrameLayout(context, attrs, defStyleAttr), IVideoPlayer,IMediaCallback {

    companion object {
        private const val TAG = "MediaVideoView"
        private var VIDEO_VIEW_ID = R.id.fin_videoview
        private const val MIN_FULLSCREEN_INTERVAL = 888L
    }
    /**
     * 进入全屏的模式 0横屏 1竖屏 2传感器自动横竖屏 3根据视频比例自动确定横竖屏      -1什么都不做
     * 对应direction： 0 竖屏  90逆时针90度， -90顺时针90度   其他：按比例自动确定
     */
    var enterFullMode: Int = 3

    /**
     * 1=SufaceRenderView, 2=TextureRenderView
     */
    private var renderViewType: Int = 0

    private lateinit var iMediaControl: IMediaControl
    private lateinit var handlePlayListener: HandlePlayListener

    lateinit var videoContainer: FrameLayout
    private lateinit var renderViewContainer: FrameLayout //suface容器
    private var iRenderView: IRenderView? = null;
    private lateinit var floatWindowHelp: FloatWindowHelp

    protected lateinit var url: String
    protected var headers: Map<String, String>? = null
    private var option: Any? = null
    /** 0网络 -1本地 1直播流 */
    private var urlMode: Int = 0
    @JvmField
    protected var currentState: Int = IVideoPlayer.STATE_NORMAL
    @JvmField
    var currentMode: Int = IVideoPlayer.MODE_WINDOW_NORMAL
    private var seekToInAdvance: Int = 0 //初始化视频完成跳进度
    private var noPlayInAdvance: Boolean = false //初始化视频完成 是否播放
    private var isBuffering: Boolean = false
    @JvmField
    protected var aspectRatio: Int = 0
    @JvmField
    protected var isMute: Boolean = false
    private var openCache: Boolean = false
    private var rate: Float = 1f
    private var mediaClass: Class<out BaseMedia> = AndroidMedia::class.java //解码器

    private var videoWidth: Int = 0
    private var videoHeight: Int = 0
    private var lastFullscreenTime: Long = 0
    private var wasFullScreen: Boolean = false
    private var wasPortrait: Boolean = false

    var isPlayerStop: Boolean = false


    //playerOption参数相关
    var startPosition: Int = 0
    var autoPlay: Boolean = true
    var isLooping: Boolean = false

    init {
        initialize(context)
    }

    private fun initialize(context: Context){
        handlePlayListener = HandlePlayListener()

        iMediaControl = ConfigManage.getInstance(context).newMediaControl(this, mediaClass)
        floatWindowHelp = FloatWindowHelp(context)

        setupVideoViews(context)
        ConfigManage.getInstance(context).addVideoView(this)
    }

    private fun setupVideoViews(context: Context){
        videoContainer = FrameLayout(context).apply { id = VIDEO_VIEW_ID }
        renderViewContainer = FrameLayout(context).apply { setBackgroundColor(Color.BLACK) }
        videoContainer.addView(renderViewContainer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        addView(videoContainer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
    }



    // region IVideoPlayer Implementation
    override fun setUp(url: String, headers: Map<String, String>?, option: Any?) {
        if (IVideoPlayer.STATE_NORMAL != currentState) release()
        this.url = url
        this.urlMode = Util.PaserUrl(url)
        this.headers = headers
        this.option = option
        setStateAndMode(IVideoPlayer.STATE_NORMAL, currentMode)
    }

    fun setUp(url: String) = setUp(url, null, null)
    fun setUp(url: String, headers: Map<String, String>?) = setUp(url, headers, null)

    /*fun updateLooping(isLooping: Boolean){
        this.isLooping = isLooping
        this.iMediaControl.setLooping(isLooping)
    }*/

    override fun play() {
        if (currentState != IVideoPlayer.STATE_PLAYING) {
            handlePlayAction()
        }
    }

    override fun prePlay() {
        noPlayInAdvance = !autoPlay
        play()
    }

    override fun seekTo(duration: Int) {
        if (isReadyForPlay()) {
            performSeek(duration.coerceAtLeast(0))
        } else {
            seekToInAdvance = duration
        }
    }

    override fun pause() {
        if (currentState == IVideoPlayer.STATE_PLAYING) {
            handlePlayAction()
        }
    }


    override fun setPlayListener(playListener: PlayListener) {
        handlePlayListener.setListener(playListener)
        post {
            playListener.onStatusAndMode(currentState,currentMode)
        }
    }

    override fun addPlayListener(playListener: PlayListener) {
        handlePlayListener.addListener(playListener)
        post {
            playListener.onStatusAndMode(currentState,currentMode)
        }
    }

    override fun removePlayListener(playListener: PlayListener) {
        handlePlayListener.removeListener(playListener)
    }


    override fun onBackPressed(): Boolean {
        return when (currentMode) {
            IVideoPlayer.MODE_WINDOW_FULLSCREEN -> {
                quitWindowFullscreen()
                true
            }
            IVideoPlayer.MODE_WINDOW_FLOAT_SYS -> true
            else -> false
        }
    }


    override fun setAspectRatio(aspectRatio: Int) {
        iRenderView?.setAspectRatio(aspectRatio)
        this.aspectRatio = aspectRatio
    }

    override fun setDecodeMedia(claxx: Class<out BaseMedia>) {
        Log.i(TAG, "播放器内核：class: $claxx")
        mediaClass = claxx
        this.iMediaControl = ConfigManage.getInstance(context).newMediaControl(this, claxx)
        //this.iMediaControl.setLooping(isLooping)
    }

    override fun openCache() {
        openCache = true
    }

    override fun isPlaying(): Boolean = iMediaControl.isPlaying()
    override fun getPosition(): Int = iMediaControl.getCurrentPosition()
    override fun getDuration(): Int = iMediaControl.getDuration()
    override fun getCurrentMode(): Int = currentMode
    override fun getCurrentState(): Int = currentState

    override fun getCurrentFrame(): Bitmap? = iRenderView?.getCurrentFrame()

    override fun release() {
        iMediaControl.release()
        removeRenderView()
        setStateAndMode(STATE_NORMAL, currentMode)
        resetParameters()
        handlePlayListener.onEvent(IVideoPlayer.EVENT_RELEASE)
    }

    //异步销毁，解决list视频销毁卡顿问题
    fun releaseInThread() {
        Thread { iMediaControl.release() }.start()
        removeRenderView()
        resetParameters()
        setStateAndMode(IVideoPlayer.STATE_NORMAL, currentMode)
        handlePlayListener.onEvent(IVideoPlayer.EVENT_RELEASE)
    }


    /*private var tempLong: Long = 0
    private var full_flag = false //标记状态栏状态
    private var orientation_flag = false //标记横竖屏状态*/

    fun checkReady(): Boolean {
        return (currentState != STATE_NORMAL
                ) and (currentState != STATE_PREPARING
                ) and (currentState != STATE_ERROR)
    }

    //全屏
    override fun enterWindowFullscreen() {
        if ((currentMode == IVideoPlayer.MODE_WINDOW_NORMAL) and canToggleFullscreen()) {
            prepareForFullscreen()
            val targetMode = determineFullscreenMode()
            applyFullscreenSettings(targetMode)
            //moveToDecorView()
            setStateAndMode(currentState, IVideoPlayer.MODE_WINDOW_FULLSCREEN)
        }
    }

    //退出全屏
    override fun quitWindowFullscreen() {
        if ((currentMode == IVideoPlayer.MODE_WINDOW_FULLSCREEN) and canToggleFullscreen()) {
            restoreScreenSettings()
            //moveBackToOriginalParent()
            setStateAndMode(currentState, IVideoPlayer.MODE_WINDOW_NORMAL)
        }
    }

    //浮窗
    override fun enterWindowFloat(floatParams: FloatParams): Boolean {
        if (currentMode != IVideoPlayer.MODE_WINDOW_NORMAL || floatParams == null) {
            return false
        }

        val success = floatWindowHelp.enterWindowFloat(videoContainer, floatParams)
        if (success) {
            val mode = if (floatParams.systemFloat) {
                IVideoPlayer.MODE_WINDOW_FLOAT_SYS
            } else {
                IVideoPlayer.MODE_WINDOW_FLOAT_ACT
            }
            setStateAndMode(currentState, mode)
        }
        return success
    }

    //退出浮窗
    override fun quitWindowFloat() {
        if (isWindowFloatMode()) {
            floatWindowHelp.quitWindowFloat()
            moveBackToOriginalParent()
            setStateAndMode(currentState, IVideoPlayer.MODE_WINDOW_NORMAL)
        }
    }

    //静音
    override fun setMute(isMute: Boolean): Boolean {
        this.isMute = isMute
        val volume = if (isMute) 0f else 1f
        return iMediaControl.setVolume(volume, volume)
    }


    override fun setSpeed(rate: Float): Boolean {
        this.rate = rate.coerceIn(0.5f, 2.0f)
        return iMediaControl.setSpeed(this.rate)
    }

    override fun setObjectFit(fitMode: String) {
        when(fitMode){
            PlayerOptions.ObjectFit.CONTAIN.value -> aspectRatio = 0
            PlayerOptions.ObjectFit.FILL.value -> aspectRatio = 3
            PlayerOptions.ObjectFit.COVER.value -> aspectRatio = 1
        }


        /*if (fitMode.isNullOrEmpty()) return
        if (this.objectFit == fitMode) return
        if(fitMode == PlayerOptions.ObjectFit.CONTAIN.value
            || fitMode == PlayerOptions.ObjectFit.COVER.value
            || fitMode == PlayerOptions.ObjectFit.FILL.value){
            this.objectFit = fitMode
        }else{
            this.objectFit = PlayerOptions.ObjectFit.CONTAIN.value
        }
        handleFitMode()*/
    }

    /*private fun handleFitMode(){
        if(videoWidth <=0 || videoHeight <=0){
            Log.d(TAG, "handleFitMode fail setVideoSize not called")
            return
        }
        val width = width
        val height = height
        if (width <= 0 || height <= 0) {
            Log.d(TAG, "handleFitMode fail not measure")
            return
        }
        if(objectFit == PlayerOptions.ObjectFit.COVER.value) {

            if((videoWidth / videoHeight).toFloat() < 1 && (width / height).toFloat() >1) {
                return
            }
            if((videoHeight / videoWidth).toFloat() < 1 && (height / width).toFloat() >1) {
                return
            }
        }
        var (dstVideoWidth, dstVideoHeight) = when(objectFit) {
            PlayerOptions.ObjectFit.FILL.value -> {
                Pair(width, height)
            }
            PlayerOptions.ObjectFit.COVER.value -> {
                var newVideoWidth = videoWidth
                var newVideoHeight = videoHeight
                var aspectRation = videoHeight/videoWidth.toFloat()
                if(enterFullMode == 0) {
                    if (aspectRation > 1) {
                        newVideoWidth = videoHeight
                        newVideoHeight = videoWidth
                    }
                    val scaleW = width.toFloat() / newVideoWidth
                    val scaleH = height.toFloat() / newVideoHeight
                    val scale = max(scaleW, scaleH)
                    val realWidth = (newVideoWidth * scale).toInt().coerceAtMost(width)
                    val realHeight = (newVideoHeight * scale).toInt().coerceAtMost(height)
                    Pair(realWidth, realHeight)
                } else {
                    val scaleW = width.toFloat() / newVideoWidth
                    val scaleH = height.toFloat() / newVideoHeight
                    val scale = max(scaleW, scaleH)
                    Pair((newVideoWidth * scale).toInt(), (newVideoHeight * scale).toInt())
                }
            }
            else -> {
                val scaleW = width.toFloat() / videoWidth
                val scaleH = height.toFloat() / videoHeight
                val scale = min(scaleW, scaleH)
                Pair((videoWidth * scale).toInt(), (videoHeight * scale).toInt())
            }
        }
        val textureView = iRenderView as TextureView
        if (textureView.width != dstVideoWidth || textureView.height != dstVideoHeight) {
            textureView.post {
                // 一定要在post执行，不然在短时间内连续执行requestLayout会被忽略。
                // 交给handler机制来处理requestLayout。(设置layoutParams会触发requestLayout)
                val lp = textureView.layoutParams as LayoutParams
                lp.width = dstVideoWidth
                lp.height = dstVideoHeight
                textureView.layoutParams = lp
            }
        }
        //todo  更改了objectFit

    }*/

    override fun getVideoWidth(): Int = videoWidth
    override fun getVideoHeight(): Int = videoHeight

    fun getFloatParams(): FloatParams = floatWindowHelp.getFloatParams()
    fun isSystemFloatMode(): Boolean = currentMode == IVideoPlayer.MODE_WINDOW_FLOAT_SYS


    // endregion


    // region IMediaCallback Implementation
    override fun onPrepared(iMediaControl: IMediaControl) {
        Log.i(TAG, "onPrepared")
        applyMediaSettings()
        handlePendingSeek()

        if (!noPlayInAdvance) {
            iMediaControl.doPlay()
            setStateAndMode(IVideoPlayer.STATE_PLAYING, currentMode)
        } else {
            noPlayInAdvance = false
            //iMediaControl.doPause()//ijk会自动播放，所以在这手动暂停
            setStateAndMode(IVideoPlayer.STATE_PAUSE, currentMode)
        }

        handlePlayListener.onEvent(IVideoPlayer.EVENT_PREPARE_END)
        handlePlayListener.onEvent(IVideoPlayer.EVENT_PLAY, 1)
    }


    override fun onCompletion(iMediaControl: IMediaControl) {
        Log.i(TAG, "onCompletion")

        setStateAndMode(IVideoPlayer.STATE_AUTO_COMPLETE, currentMode)
        handlePlayListener.onEvent(IVideoPlayer.EVENT_COMPLETION)

        if(isLooping) {
            seekTo(0)
        }
    }

    override fun onSeekComplete(iMediaControl: IMediaControl) {
        Log.i(TAG, "onSeekComplete")
        handlePlayListener.onEvent(IVideoPlayer.EVENT_SEEK_COMPLETION,getPosition())
    }

    override fun onInfo(iMediaControl: IMediaControl, what: Int, extra: Int) {
        Log.i(TAG, "onInfo what=$what extra=$extra")

        handleStreamInterruption(what, extra)
        handleBufferingEvents(what)
    }


    override fun onVideoSizeChanged(iMediaControl: IMediaControl, width: Int, height: Int) {
        Log.i(TAG, "onVideoSizeChanged width:$width height:$height")

        iRenderView?.setVideoSize(width, height)
        videoWidth = width
        videoHeight = height

        handlePlayListener.onEvent(IVideoPlayer.EVENT_VIDEOSIZECHANGE, width, height)
    }

    override fun onError(iMediaControl: IMediaControl, what: Int, extra: Int) {
        Log.e(TAG, "onError what:$what extra:$extra")

        if (shouldIgnoreError(what, extra)) return

        showErrorToast(what, extra)
        saveCurrentPosition()
        iMediaControl.release()
        setStateAndMode(IVideoPlayer.STATE_ERROR, currentMode)
        handlePlayListener.onEvent(IVideoPlayer.EVENT_ERROR, what, extra)
    }

    override fun onBufferingUpdate(iMediaControl: IMediaControl, bufferProgress: Float) {
        updateBufferProgress(bufferProgress)
        handlePlayListener.onEvent(
            IVideoPlayer.EVENT_BUFFERING_UPDATE,
            (bufferProgress * 100).toInt()
        )
    }


    //给子类覆盖
    protected open fun onBuffering(isBuffering: Boolean) {
    }

    //给子类覆盖 0~progressMax
    protected open fun setBufferProgress(bufferProgress: Float) {
    }

    protected open fun showWifiDialog(): Boolean {
        // For subclasses to override
        return false
    }
    //-----------解码器回调end-----------------
    //-----------各种流程逻辑start-----------------
    //初始化一些变量
    protected fun resetParameters() {
        videoWidth = 0
        videoHeight = 0
        seekToInAdvance = startPosition*1000
        noPlayInAdvance = false
        isBuffering = false
    }

    /**
     * 设置播放状态
     */
    private fun setStateAndMode(status: Int, mode: Int) {
        Log.i(TAG, "setStateAndMode status:$status mode:$mode")
        if (Looper.getMainLooper() == Looper.myLooper()) {
            updateUIWithStateAndMode(status, mode)
        } else {
            post { updateUIWithStateAndMode(status, mode) }
        }
    }

    /**
     * 状态和模式变更，通过ui更新
     */
    open fun updateUIWithStateAndMode(status: Int, mode: Int) {
        Log.i(TAG, "updateUIWithStateAndMode status:$status mode:$mode")
        manageScreenOnFeature(status)
        val oldState = currentState
        val oldMode = currentMode

        currentState = status
        currentMode = mode

        if (oldState != status || oldMode != mode) {
            handlePlayListener.onStatusAndMode(status,mode)
        }
    }

    private fun manageScreenOnFeature(status: Int) {
        if (status == IVideoPlayer.STATE_PLAYING) {
            Util.keepScreenOn(context)
        } else {
            Util.keepScreenOff(context)
        }
    }

    fun handlePlayAction() {
        if (TextUtils.isEmpty(url)) {
            showNoUrlToast()
            return
        }

        when (currentState) {
            IVideoPlayer.STATE_NORMAL -> prepareMediaPlayerWithChecks()
            IVideoPlayer.STATE_PLAYING -> pausePlayback()
            IVideoPlayer.STATE_PAUSE -> resumePlayback()
            IVideoPlayer.STATE_AUTO_COMPLETE, IVideoPlayer.STATE_ERROR -> restartPlayback()
        }
    }

    private fun prepareMediaPlayerWithChecks() {
        if (urlMode >= 0 && !Util.isWifiConnected(context) && showWifiDialog()) {
            return
        }
        prepareMediaPlayer()
    }

    private fun pausePlayback() {
        iMediaControl.doPause()
        setStateAndMode(IVideoPlayer.STATE_PAUSE, currentMode)
        handlePlayListener.onEvent(IVideoPlayer.EVENT_PAUSE)
    }

    private fun resumePlayback() {
        if(isPlayerStop){
            iMediaControl.seekTo(0)
            isPlayerStop = false
        }
        iMediaControl.doPlay()
        setStateAndMode(IVideoPlayer.STATE_PLAYING, currentMode)
        handlePlayListener.onEvent(IVideoPlayer.EVENT_PLAY)
    }

    private fun restartPlayback() {
        prepareMediaPlayer()
    }

    private fun prepareMediaPlayer() {

        removeRenderView()
        val finalUrl = prepareVideoUrl()

        if (iMediaControl.doPrepare(context, finalUrl, headers, option)) {
            addRenderView()
            setStateAndMode(IVideoPlayer.STATE_PREPARING, currentMode)
            handlePlayListener.onEvent(IVideoPlayer.EVENT_PREPARE_START)
        }
    }

    private fun prepareVideoUrl(): String {
        return url
        /*return if (openCache && urlMode == 0) {
            CacheManager.buildCacheUrl(context, url, headers)
        } else {
            url
        }*/
    }

    private fun addRenderView() {
        iRenderView = ConfigManage.getInstance(context).getIRenderView(context, renderViewType)

        iRenderView?.apply {
            addRenderCallback(createRenderCallback())
            setAspectRatio(aspectRatio)
            renderViewContainer.addView(get(), LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER))
        }
    }

    private fun createRenderCallback(): IRenderView.IRenderCallback {
        return object : IRenderView.IRenderCallback {
            override fun onSurfaceCreated(holder: IRenderView, width: Int, height: Int) {
                holder.bindMedia(iMediaControl)
            }

            override fun onSurfaceChanged(holder: IRenderView, format: Int, width: Int, height: Int) {
                // No-op
            }

            override fun onSurfaceDestroyed(holder: IRenderView) {
                if (holder is SufaceRenderView) {
                    iMediaControl.setDisplay(null)
                }
            }
        }
    }

    private fun removeRenderView() {
        renderViewContainer.removeAllViews()
        iRenderView?.removeRenderCallback()
        iRenderView = null
    }

    private fun performSeek(time: Int) {
        when (currentState) {
            IVideoPlayer.STATE_PLAYING, IVideoPlayer.STATE_PAUSE -> {
                iMediaControl.seekTo(time)
            }
            IVideoPlayer.STATE_AUTO_COMPLETE -> {
                iMediaControl.seekTo(time)
                iMediaControl.doPlay()
                setStateAndMode(IVideoPlayer.STATE_PLAYING, currentMode)
                handlePlayListener.onEvent(IVideoPlayer.EVENT_PLAY)
            }
        }
        handlePlayListener.onEvent(IVideoPlayer.EVENT_SEEK_TO, time)
    }

    fun isReadyForPlay(): Boolean {
        return currentState != IVideoPlayer.STATE_NORMAL &&
                currentState != IVideoPlayer.STATE_PREPARING &&
                currentState != IVideoPlayer.STATE_ERROR
    }

    fun isWindowFloatMode(): Boolean {
        return currentMode == IVideoPlayer.MODE_WINDOW_FLOAT_SYS ||
                currentMode == IVideoPlayer.MODE_WINDOW_FLOAT_ACT
    }

    private fun canToggleFullscreen(): Boolean {
        val now = System.currentTimeMillis()
        val timeSinceLastToggle = now - lastFullscreenTime
        if (timeSinceLastToggle > MIN_FULLSCREEN_INTERVAL) {
            lastFullscreenTime = now
            return true
        }
        return false
    }

    private fun determineFullscreenMode(): Int {
        return when (enterFullMode) {
            3 -> if (videoHeight > videoWidth) 1 else 0
            else -> enterFullMode
        }
    }

    private fun prepareForFullscreen() {
        Util.hideBottomUIMenu(context)
        wasFullScreen = Util.setFullScreen(context)
        wasPortrait = Util.isScreenOrientationPortrait(context)
    }

    private fun applyFullscreenSettings(mode: Int) {
        when (mode) {
            0 -> Util.setLandscape(context)//横屏
            1 -> Util.setPortrait(context)//竖屏
            2 -> Util.setSensor(context)
        }
    }

    private fun restoreScreenSettings() {
        Util.showBottomUIMenu(context)

        if (wasFullScreen) {
            Util.setFullScreen(context)
        } else {
            Util.clearFullScreen(context)
        }

        if (wasPortrait) {
            Util.setPortrait(context)
        } else {
            Util.setLandscape(context)
        }
    }

    private fun moveToDecorView() {
        (videoContainer.parent as? ViewGroup)?.removeView(videoContainer)
        //val decorView = Util.scanForActivity(context).window.decorView as ViewGroup
        //decorView.addView(videoContainer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        addView(videoContainer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
    }

    private fun moveBackToOriginalParent() {
        (videoContainer.parent as? ViewGroup)?.removeView(videoContainer)
        addView(videoContainer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
    }

    private fun applyMediaSettings() {
        setMute(isMute)
        //setSpeed(rate)   //在播放前设置了播放速度会直接播放
    }

    private fun handlePendingSeek() {
        //if (seekToInAdvance > 0) {
        //todo
            iMediaControl.seekTo(seekToInAdvance)
            //handlePlayListener.onEvent(IVideoPlayer.EVENT_SEEK_TO, seekToInAdvance)
            //seekToInAdvance = 0
        //}
    }

    private fun handleStreamInterruption(what: Int, extra: Int) {
        if ((what == 804 || what == 805) && extra == -1004) {
            onError(iMediaControl, what, extra)
        }
    }

    private fun handleBufferingEvents(what: Int) {
        when (what) {
            IMediaControl.MEDIA_INFO_BUFFERING_START -> {
                isBuffering = true
                onBuffering(true)
                handlePlayListener.onEvent(IVideoPlayer.EVENT_BUFFERING_START, getPosition())
            }
            IMediaControl.MEDIA_INFO_BUFFERING_END -> {
                isBuffering = false
                onBuffering(false)
                handlePlayListener.onEvent(IVideoPlayer.EVENT_BUFFERING_END, getPosition())
            }
        }
    }

    private fun shouldIgnoreError(what: Int, extra: Int): Boolean {
        return what == 38 || extra == -38 || extra == -19
    }

    private fun showErrorToast(what: Int, extra: Int) {
        Toast.makeText(context, "Error: $what,$extra", Toast.LENGTH_SHORT).show()
    }

    private fun saveCurrentPosition() {
        seekToInAdvance = getPosition()
    }

    private fun updateBufferProgress(bufferProgress: Float) {
        setBufferProgress(bufferProgress)
    }

    private fun showNoUrlToast() {
        Toast.makeText(context, context.getString(R.string.no_url), Toast.LENGTH_SHORT).show()
    }

    private fun notifyCurrentState(listener: PlayListener) {
        post {
            /*listener.onMode(currentMode)
            listener.onStatus(currentState)*/
            listener.onStatusAndMode(currentState,currentMode)
        }
    }
    // endregion

}